﻿using System;
using System.Collections.Generic;
using System.Reflection;
using Eff.Commons;

namespace Eff.Web
{
    /// <summary>
    /// 表单帮助类
    /// </summary>
    public class Form
    {
        ///<summary>
        /// 把form填充到model中
        ///</summary>
        ///<param name="form"></param>
        ///<param name="model"></param>
        public static void BindFormToModel<T>(IDictionary<string, object> form, ref T model)
        {
            //反射把form的值填充到model中
            Type t = typeof(T);
            foreach (PropertyInfo p in t.GetProperties())
            {
                string fieldName = p.Name;
                object value;
                if (form.TryGetValue(fieldName, out value))
                {
                    try
                    {
                        if (p.PropertyType == typeof(bool)) //mvc的checkbox获取有问题，选中获取值为true,false。没选中为false
                            p.SetValue(model, value.ToString().ToLower().Contains("true"), null);
                        else
                            p.SetValue(model, Convert.ChangeType(value.ToString(), p.PropertyType), null);
                    }
                    catch (Exception e)
                    {
                        LogHelper.Log.Error(fieldName + "填充失败," + e.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 把model填充到字典中
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <param name="form"></param>
        public static void BindModelToFormDic<T>(T model, ref IDictionary<string, object> form)
        {
            //反射把form的值填充到model中
            Type t = typeof(T);
            foreach (PropertyInfo p in t.GetProperties())
            {
                string fieldName = p.Name;
                object value = p.GetValue(model, null);
                if (!form.ContainsKey(fieldName))
                    form.Add(fieldName, value);
                else
                    form[fieldName] = value;
            }
        }
    }
}
